package leetcode.code1156;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution2 implements IDebug {

	public int maxRepOpt1(String text) {
		char[] cs = text.toCharArray();
		int[] dics = new int[26];
		for (char c : cs) {
			dics[c - 'a'] += 1;
		}
		int ans = 0;
		int l = 0;
		Integer A = null, B = null;
		int a = 0, b = 0;
		int len = cs.length;
		for (int r = 0; r < len; r++) {
			int c = cs[r];
			if (A == null) {
				A = c;
				a = 1;
			} else if (c != A && B == null) {
				B = c;
				b = 1;
			} else {
				if (c == A) {
					if (a <= 1 && b <= 1) {
						a++;
					} else {
						if (a > 1) {
							a++;
						} else {
							ans = this.len(a, A, B, dics, l, r, ans);
							A = c;
							a = 1;
							B = null;
							b = 0;
						}
					}
				} else if (c == B) {
					if (a <= 1 && b <= 1) {
						b++;
					} else {
						if (b > 1) {
							b++;
						} else {
							ans = this.len(a, A, B, dics, l, r, ans);
							A = c;
							a = 1;
							B = null;
							b = 0;
						}
					}
				} else {
					ans = this.len(a, A, B, dics, l, r, ans);
					A = c;
					a = 1;
					B = null;
					b = 0;
				}
			}
		}
		if (A != null && B != null) {
			ans = this.len(a, A, B, dics, l, len, ans);
		}
		return ans;
	}

	private int len(int a, int A, int B, int[] dics, int l, int r, int ans) {
		int who = a > 1 ? A : B;
		if (dics[who - 'a'] > r - l) {
			ans = Math.max(ans, r - l);
		} else {
			ans = Math.max(ans, r - l - 1);
		}
		return ans;
	}

	@Override
	public void debug4() {
		HelpDebug.compare(4, this.maxRepOpt1("aaabbaaa"));
		HelpDebug.compare(6, this.maxRepOpt1("aaabaaa"));
		HelpDebug.compare(3, this.maxRepOpt1("ababa"));
		HelpDebug.compare(5, this.maxRepOpt1("aaaaa"));
		HelpDebug.compare(1, this.maxRepOpt1("abcdef"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
